package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.entity.ApplicationCompany;
import com.example.haoqisystem.entity.Teacher;
import com.example.haoqisystem.request.CreateApplicationCompanyRequest;
import com.example.haoqisystem.request.CreateTeacherRequest;
import com.example.haoqisystem.request.UpdateApplicationCompanyRequest;
import com.example.haoqisystem.request.UpdateTeacherRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.respository.ApplicationCompanyRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor(onConstructor_ ={@Autowired} )
@Slf4j
public class ApplicationCompanyService {

    private final ApplicationCompanyRepository applicationCompanyRepository;

    //验证密码
    public boolean isPassword(String pwd){
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,16}$";
        return pwd.matches(regex);
    }

    //验证邮箱格式
    public boolean isEmail(String email){
        String regex="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        return email.matches(regex);
    }

    //验证手机号
    public boolean isValidPhoneNumber(String phoneNumber) {
        // 移除号码中的空格、括号、破折号等特殊字符
        String cleanedNumber = phoneNumber.replaceAll("[\\s()-]+", "");

        // 验证手机号格式
        String regex = "^(\\+?\\d{1,3})?[-.\\s]?\\(?\\d{1,4}\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}$";
        return cleanedNumber.matches(regex);
    }


    public BaseResponse<ApplicationCompany> register(CreateApplicationCompanyRequest request) {
        if(!isPassword(request.getPassword())){
            return new BaseResponse<>("密码格式错误！需要8-16位至少包含大小写字母和数字",false,null);
        }
        try{
            ApplicationCompany company=new ApplicationCompany();
            BeanUtil.copyProperties(request,company, CopyOptions.create().setIgnoreNullValue(true));
            ApplicationCompany company1=applicationCompanyRepository.save(company);
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true,company1);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    public BaseResponse<ApplicationCompany> update(UpdateApplicationCompanyRequest request) {
        if(request.getId()==null){
            return new BaseResponse<>("需要培训公司id！",false,null);
        }
        try{
            Optional<ApplicationCompany> optionalApplicationCompany=applicationCompanyRepository.findByIdAndDeletedFalse(request.getId());
            if(!optionalApplicationCompany.isPresent()){
                return new BaseResponse<>("该公司不存在！",false,null);
            }
            ApplicationCompany company= optionalApplicationCompany.get();
            BeanUtil.copyProperties(request,company,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,applicationCompanyRepository.save(company));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    public BaseResponse<List<ApplicationCompany>> queryList(String name,Long id) {
        try{
            Specification<ApplicationCompany> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                if(name!=null&&!name.equals("")){
                    String nameLike="%"+name+"%";
                    predicates.add(builder.like(root.get("companyName"),nameLike));
                }
                if(id!=null&&!id.equals("")){
                    predicates.add(builder.equal(root.get("id"),id));
                }
                predicates.add(builder.equal(root.get("deleted"),false));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<ApplicationCompany> list=applicationCompanyRepository.findAll(specification);
            Collections.reverse(list);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,list);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    public BaseResponse<ApplicationCompany> detail(Long id) {
        try{
            Optional<ApplicationCompany> applicationCompanyOptional=applicationCompanyRepository.findByIdAndDeletedFalse(id);
            if(!applicationCompanyOptional.isPresent()){
                return new BaseResponse<>("该培训公司不存在！",false,null);
            }
            ApplicationCompany company=applicationCompanyOptional.get();
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,company);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    public BaseResponse<String> delete(Long id) {
        try{
            Optional<ApplicationCompany> applicationCompanyOptional=applicationCompanyRepository.findByIdAndDeletedFalse(id);
            if(!applicationCompanyOptional.isPresent()){
                return new BaseResponse<>("该申请公司不存在或已被删除！",false,null);
            }
            ApplicationCompany company=applicationCompanyOptional.get();
            company.setDeleted(true);
            applicationCompanyRepository.save(company);
            return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,null);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    public BaseResponse<ApplicationCompany> login(String account, String password) {
        try{
            Optional<ApplicationCompany> applicationCompanyOptional=applicationCompanyRepository.findByAccountAndDeletedFalse(account);
            if(!applicationCompanyOptional.isPresent()){
                return new BaseResponse<>("该公司不存在！",false,null);
            }
            ApplicationCompany company= applicationCompanyOptional.get();
            if(!password.equals(company.getPassword())){
                return new BaseResponse<>("登录失败，密码错误！",false,null);
            }
            return new BaseResponse<>("登录成功！",true,company);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //重置密码
    public BaseResponse<String> resetPassword(Long id, String password) {
        try{
            Optional<ApplicationCompany> applicationCompanyOptional=applicationCompanyRepository.findByIdAndDeletedFalse(id);
            if(!applicationCompanyOptional.isPresent()){
                return new BaseResponse<>("该公司不存在！", false, null);
            }
            ApplicationCompany company=applicationCompanyOptional.get();
            if(company.getPassword().equals(password)){
                return new BaseResponse<>("请勿输入重复的密码！", false, null);
            }
            company.setPassword(password);
            applicationCompanyRepository.save(company);
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,"密码重置成功！");
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }
}
